package com.yunnuo.system.role.service.impl;

import com.yunnuo.system.comm.util.Empty;
import com.yunnuo.system.comm.util.StringUtils;
import com.yunnuo.system.comm.util.page.TableDataInfo;
import com.yunnuo.system.role.dao.IRoleDao;
import com.yunnuo.system.role.dao.IRoleMenuDao;
import com.yunnuo.system.role.entity.Role;
import com.yunnuo.system.role.entity.RoleMenu;
import com.yunnuo.system.role.service.IRoleService;
import com.yunnuo.system.users.entity.PageParams;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by w_weihf on 2018/8/3.
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IRoleMenuDao roleMenuDao;

    @Override
    public Set<String> selectRoleKeys(String userId) {
        List<Role> perms =  roleDao.selectAllRoleByUserId(userId);
        Set<String> permsSet = new HashSet<String>();
        for (Role perm : perms)
        {
            if (StringUtils.isNotNull(perms))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<Role> selectRolesByUserId(String userId) {
        return roleDao.selectAllRoleByUserId(userId);
    }

    /**
     * 默认角色  在用户管理新增角色时   默认勾选
     * @return
     */
    @Override
    public List<Role> selectRoleAll() {
        return roleDao.findAll();
    }

    @Override
    public int deleteRoleById(String roleId) {
        try{
            roleDao.delete(roleId);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 修改用户时展示的角色信息，对flag进行处理
     * flag-true选中
     * @param userId
     * @return
     */
    @Override
    public List<Role> selectEditRole(String userId) {
        //所有角色列表
        List<Role> roles=roleDao.findAll();

        //用户所拥有的角色
        List<Role> roles2=roleDao.selectAllRoleByUserId(userId);
        for (Role r:roles ) {
            r.setFlag("false");
            if(roles2.contains(r.getId())){
                r.setFlag("true");
            }
        }
        return roles;
    }
    /**
     * 分页查询
     * @param pageParams
     * @param pageRequest
     * @return
     */
    @Override
    public TableDataInfo selectRoleListByPageParams(PageParams pageParams, PageRequest pageRequest) {
        TableDataInfo dataInfo=new TableDataInfo();

        Specification<Role> spec=new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> namePath=root.get("roleName");
                String value=pageParams.getSearchValue();
                if (Empty.isNotEmpty(value)){
                    query.where(cb.like(namePath,"%"+value+"%"));
                }
                return null;
            }
        };
        Page<Role> roles=( Page<Role>) roleDao.findAll(spec,pageRequest);

        dataInfo.setRows(roles.getContent());
        dataInfo.setTotal(roles.getTotalElements());
        return dataInfo;
    }

    @Override
    public String checkRoleNameUnique(Role role) {
        int count=0 ;
        if(null!=role.getId()&&!"".equals(role.getId())){
            count= roleDao.countAllByIdAndRoleName(role.getId(),role.getRoleName());
            if (count==1){
                return "0";
            }
        }
        return roleDao.countAllByRoleName(role.getRoleName())+"";
    }
    /**
     * 保存角色及权限
     * @param role
     * @param menuIds
     */
    @Override
    public void save(Role role, String menuIds) {
        try {
            /*
             判断角色是否存在，如果存在，先删除对应的菜单
             */
            if(null!=role&&!"".equals(role.getId())){
                roleMenuDao.deleteAllByRoleId(role.getId());
            }

            Role newRole= roleDao.save(role);
            if(null!=newRole&&!"".equals(newRole.getId())){
                String[] menuIdStrs=menuIds.split(",");
                for (String menuId:menuIdStrs){
                    RoleMenu roleMenu=new RoleMenu();
                    roleMenu.setMenuId(menuId);
                    roleMenu.setRoleId(newRole.getId());
                    roleMenuDao.save(roleMenu);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void addVO(Role vo) throws ServiceException {
        roleDao.save(vo);

    }

    @Override
    public void updateVO(Role vo) throws ServiceException {
        roleDao.saveAndFlush(vo);
    }

    @Override
    public void delList(String[] ids) throws ServiceException {
    }

    @Override
    public void deleteVo(String id) throws ServiceException {
        roleDao.delete(id);
    }

    @Override
    public List<Role> findList() throws ServiceException {
        return null;
    }

    @Override
    public List<?> findList(Role vo, String other) throws ServiceException {
        return null;
    }


    @Override
    public Role findVO(String id) throws ServiceException {
        return roleDao.findOne(id);
    }
}
